#include "dbhelper.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

dbhelper::dbhelper(){
    mysql_init(&conn);
    res_ptr = NULL;
}

dbhelper::~dbhelper(){
    delete res_ptr;
}

bool dbhelper::connect(char* host, char* username, char* passwd){
    
    
    if(mysql_real_connect(&conn,host,username,passwd,NULL,0,NULL,0))
        return true;
    else
        return false;
}
bool dbhelper::connect(char* host, char* username, char* passwd, char* dbname){
    
    mysql_init(&conn);
    if(mysql_real_connect(&conn,host,username,passwd,dbname,0,NULL,0))
        return true;
    else
        return false;
}

MYSQL_RES* dbhelper::query(char* query){
    int res;
    res = mysql_query(&conn,query);
    if(res){
        return NULL;
    }
    else{
        res_ptr = mysql_store_result(&conn);
        return res_ptr;
    }
}

void dbhelper::close(){
    mysql_close(&conn);
    mysql_library_end();
}

bool dbhelper::setuft8(){
    int res;
    res = mysql_query(&conn,"SET NAMES 'uft8'");
    if(!res) return true;
    else return false;
}

char*** dbhelper::parse_res(int *row, int *col,int top){
    if(res_ptr){
        if(res_ptr->row_count ==0)
                return NULL;
        else{
            //
            if(top !=NULL || top !=0){
                //row = new int;
                cout<<top<<endl;
                *row = top;
            }
            else *row = res_ptr->row_count;
            
            MYSQL_ROW sqlrow;
            
            char*** ptr;
            *col = res_ptr->field_count;
            ptr = new char**[*row];            
            for(int i=0;i<res_ptr->row_count;i++){
                ptr[i] = new char*[*col];
            }
                        
            int index=0;
            while(sqlrow = mysql_fetch_row(res_ptr)){               
                for(int i=0;i<*col;i++){                    
                    ptr[index][i]= sqlrow[i];                                                            
                }                
                index++;
            }            
            return ptr;            
        }
    }
    else{    
        return NULL;
    }
    
}
